package com.fingard.dsp.bank.directbank.vbao01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IQRPay;
import com.fingard.dsp.bank.reqrespobj.qrpay.ReqGenQRInfo;
import com.fingard.dsp.bank.reqrespobj.qrpay.RetAtsGenQRInfo;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.vbao.service.trade.VbaoChargeSystemHandler;
import com.vbao.service.trade.bean.request.CashierDeskQueryRequest;
import com.vbao.service.trade.bean.request.OneQRCodePaymentRequest;
import com.vbao.service.trade.bean.request.TradeRequestXml;
import com.vbao.service.trade.utils.TradeCodeEnum;

import java.net.URLDecoder;

public class VBAO01QRPay extends VBAO01Base implements IQRPay {
	@Override
	public RetAtsGenQRInfo genQRInfo(ReqGenQRInfo p_req) {
		RetAtsGenQRInfo retAts = new RetAtsGenQRInfo();
		
		retAts.rdSeq = p_req.rdSeq;
		retAts.respCode = "0";
		retAts.respInfo = reqHeader.bankCode + "暂不支持该接口";
		retAts.qrInfo = "";

		return retAts;
	}

	@Override
	public RetAtsUnifiedOrder submitQROrder(ReqUnifiedOrder p_req) {
		RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
		retAts.rdSeq = p_req.rdSeq;

		try {
			ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
			if (actItem != null) {
				String customerNo = p_req.merchantId;
				if (StringHelper.isNullOrEmpty(customerNo)) {
					customerNo = actItem.merchantId;
				}

				String goodNo = getBankConfig().getValueAsString("QRPayGoodNo");
				if (StringHelper.isNullOrEmpty(goodNo)) {
					retAts.respCode = "-1";
					retAts.respInfo = "[商户商品代号:QRPayGoodNo]内容为空,请检查config.xml相关配置!";
				}

				// 统一下单业务参数
				OneQRCodePaymentRequest oneQRPaySubmitRequest = new OneQRCodePaymentRequest();

				oneQRPaySubmitRequest.setVersion("6.0"); /* 版本号 */

				oneQRPaySubmitRequest.setInputCharset("UTF-8"); /* 字符集(固定为UTF-8) */

				oneQRPaySubmitRequest.setSignType("MD5"); /* 加密方式(固定为MD5) */

				oneQRPaySubmitRequest.setCustomerNo(customerNo); /* 商户号 */

				oneQRPaySubmitRequest.setGoodNo(goodNo); /* 商户商品代号 */

				oneQRPaySubmitRequest.setOrderNo(p_req.rdSeq); /* 商户订单号 */

				oneQRPaySubmitRequest.setOrderAmount(p_req.amount); /* 商户订单金额 */

				oneQRPaySubmitRequest.setProductName(p_req.description); /* 商品名称(保单号)，在银行允许下为银行摘要 */

				oneQRPaySubmitRequest.setProductDesc(""); /* 商品的描述信息（保单描述） */

				oneQRPaySubmitRequest.setNotifyUrl(actItem.notifyURL); /* 支付完成后，服务器异步通知商户的接口地址，格式以http:或https:打头 */

				oneQRPaySubmitRequest.setBranch1(""); /* 商户下属一级分支机构 */

				oneQRPaySubmitRequest.setBranch2(""); /* 商户下属二级分支机构 */

				oneQRPaySubmitRequest.setBranch3(""); /* 商户下属三级分支机构 */

				oneQRPaySubmitRequest.setSalesChannel(""); /* 商户销售渠道 */

				oneQRPaySubmitRequest.setCustProductCode(""); /* 商户产品代码 */

				oneQRPaySubmitRequest.setExpiredTime(Format.DateTimeFormat.format(p_req.getTimeExpire())); /* 二维码失效时间，精确到秒，格式必须为yyyy-mm-dd hh:mm:ss。此字段为空表示二维码长期有效 */

				oneQRPaySubmitRequest.setExt1(p_req.attach); /* 备注1 */

				oneQRPaySubmitRequest.setExt2(""); /* 备注 2*/

				if ("1".equals(p_req.realNameFlag) && "0".equals(p_req.realNameType)) {
					String systemFlag = getBankConfig().getMapValueByKey("systemFlag", p_req.systemFlag);
					if (!StringHelper.isNullOrEmpty(systemFlag)) {
						oneQRPaySubmitRequest.setIsAuthenti(systemFlag); /* 中保信实名地区必填=Z */
					} else {
						oneQRPaySubmitRequest.setIsAuthenti("Z");
					}
				}

				/*String systemFlag = getBankConfig().getMapValueByKey("systemFlag", "Z");
				if (!StringHelper.isNullOrEmpty(systemFlag)) {
					oneQRPaySubmitRequest.setIsAuthenti(systemFlag);*//* 中保信实名地区必填=Z *//*
				} else {
					oneQRPaySubmitRequest.setIsAuthenti("Z");
				}*/

				// 组装请求报文
				VbaoChargeSystemHandler vbaoHandler = new VbaoChargeSystemHandler();
				TradeRequestXml tradeRequestXml = vbaoHandler.creatRequestXml(oneQRPaySubmitRequest, actItem.saltKey, getCharset(), TradeCodeEnum.ONEQRCOCE_PAY.getCode());

				WriteBankLogLn2("微保一码付获取二维码加密前明文:\r\n" + tradeRequestXml.getOriRequestXml());
				WriteBankLogLn2("微保一码付获取二维码请求数据:\r\n" + tradeRequestXml.getRequestXml());

				if (tradeRequestXml.getErrMsg() == null) {
					String oneQRPaySubmitURL = bankFront.getUrl("oneQRPaySubmit");
					if (StringHelper.isNullOrEmpty(oneQRPaySubmitURL)) {
						retAts.respCode = "-1";
						retAts.respInfo = "[获取二维码地址:oneQRPaySubmit]内容为空,请检查BankFront.xml相关配置!";

						return retAts;
					}

					WriteBankLogLn2("微保一码付获取二维码提交地址:" + oneQRPaySubmitURL);

					// 发送微保并获取返回
					String tmpOneQRPayRespXml = vbaoHandler.http(oneQRPaySubmitURL, tradeRequestXml.getRequestXml(), getCharset());
					WriteBankLogLn2("微保一码付获取二维码响应数据:\r\n" + tmpOneQRPayRespXml);

					if (StringHelper.hasAnyChar(tmpOneQRPayRespXml)) {
						// 进行解密
						String tmpOneQRPayOriXml = Base64vbao.decode(tmpOneQRPayRespXml, getCharset());
						//tmpOneQRPayOriXml = new String(tmpOneQRPayOriXml.getBytes(), getCharset());
						WriteBankLogLn2("微保一码付获取二维码解密后明文:\r\n" + tmpOneQRPayOriXml);

						// 执行验签
						boolean flag = vbaoHandler.verifySignature(tmpOneQRPayOriXml, actItem.saltKey, getCharset());
						if (flag) {
							String tmpRetStr = URLDecoder.decode(tmpOneQRPayOriXml, getCharset());

							StringBuilder tmpSbMsg = new StringBuilder();
							XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr, tmpSbMsg);

							if (tmpBkReader != null) {
								String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
								if (tmpReturnCode.equals("T")) {
									retAts.respCode = "0";
									retAts.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
									retAts.rdSeq = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderNo");
									retAts.qrInfo = tmpBkReader.getFirstText("/TResponse/OrderInfo/CodeUrl");
									retAts.transState = "success";
									retAts.payInfoCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");
								} else {
									retAts.respCode = "-1";
									retAts.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
								}
							} else {
								retAts.respCode = "-1";
								retAts.respInfo = tmpSbMsg.toString();
							}
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = "微保一码付获取二维码本地验签失败!";
						}
					}  else {
						retAts.respCode = "-1";
						retAts.respInfo = "微保一码付获取二维码返回内容为空,请联系微保相关技术人员!";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tradeRequestXml.getErrMsg();
				}
			} else {
				retAts.respCode = "0";
				retAts.respInfo = "未找到账户[" + p_req.ownAct + "]商户配置信息";
				retAts.qrInfo = "";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}

	@Override
	public RetAtsQueryOrder queryQRPay(ReqQueryOrder p_req) {
		RetAtsQueryOrder retAts = new RetAtsQueryOrder();
		retAts.rdSeq = p_req.rdSeq;

		try {
			ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
			if (actItem != null) {
				String customerNo = p_req.merchantId;
				if (StringHelper.isNullOrEmpty(customerNo)) {
					customerNo = actItem.merchantId;
				}

				CashierDeskQueryRequest oneQRPayQueryRequest = new CashierDeskQueryRequest();

				// 统一下单查询业务参数
				oneQRPayQueryRequest.setVersion("6.0"); /* 版本号 */

				oneQRPayQueryRequest.setInputCharset(getCharset()); /* 字符集(固定为UTF-8) */

				oneQRPayQueryRequest.setSignType("MD5"); /* 加密方式(固定为MD5) */

				oneQRPayQueryRequest.setCustomerNo(customerNo); /* 商户号 */

				oneQRPayQueryRequest.setPayDate(Format.Date8Format.format(p_req.getBgnDateTime())); /* 支付日期  (格式yyyyMMdd) */

				oneQRPayQueryRequest.setOrderNo(p_req.rdSeq); /* 商户订单号 */

				oneQRPayQueryRequest.setSerialNo(""); /* 微保支付流水号 */

				// 组装发送报文
				VbaoChargeSystemHandler vbaoHandler = new VbaoChargeSystemHandler();
				TradeRequestXml tradeRequestXml = vbaoHandler.creatRequestXml(oneQRPayQueryRequest, actItem.saltKey, getCharset(), TradeCodeEnum.CASHIER_PAY_QUERY.getCode());

				WriteBankLogLn2("微保一码付订单状态查询加密前明文:\r\n" + tradeRequestXml.getOriRequestXml());
				WriteBankLogLn2("微保一码付订单状态查询请求数据:\r\n" + tradeRequestXml.getRequestXml());

				if(tradeRequestXml.getErrMsg() == null) {
					String oneQRPayQueryURL = bankFront.getUrl("oneQRPayQuery");
					if (StringHelper.isNullOrEmpty(oneQRPayQueryURL)) {
						retAts.respCode = "-1";
						retAts.respInfo = "[一码付订单状态查询服务地址:oneQRPayQuery]内容为空,请检查BankFront.xml相关配置!";

						return retAts;
					}

					WriteBankLogLn2("微保一码付订单状态查询服务地址:" + oneQRPayQueryURL);

					// 发送微保并获取返回
					String oneQRPayQueryRespXml = vbaoHandler.http(oneQRPayQueryURL, tradeRequestXml.getRequestXml(), getCharset());
					oneQRPayQueryRespXml = new String(oneQRPayQueryRespXml.getBytes(), getCharset());
					WriteBankLogLn2("微保一码付订单状态查询响应数据:\r\n" + oneQRPayQueryRespXml);

					if(StringHelper.hasAnyChar(oneQRPayQueryRespXml)) {
						//进行解密
						String oneQRPayOriRespXml = Base64vbao.decode(oneQRPayQueryRespXml, getCharset());
						//oneQRPayOriRespXml = new String(oneQRPayOriRespXml.getBytes(), getCharset());
						WriteBankLogLn2("微保一码付订单状态查询解密后明文:\r\n" + oneQRPayOriRespXml);

						//执行验签
						boolean flag = vbaoHandler.verifySignature(oneQRPayOriRespXml, actItem.saltKey, getCharset());
						if(flag) {
							String tmpRetStr = URLDecoder.decode(oneQRPayOriRespXml, getCharset());

							StringBuilder tmpSbMsg = new StringBuilder();
							XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr, tmpSbMsg);

							if (tmpBkReader != null) {
								String tmpReturnCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ResultCode");
								if (tmpReturnCode.equals("T")) {
									String errorCode = tmpBkReader.getFirstText("/TResponse/ResultInfo/ErrCode");

									retAts.respCode = "0";
									retAts.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
									retAts.rdSeq = tmpBkReader.getFirstText("/TResponse/OrderInfo/OrderNo");
									retAts.transState = StringHelper.joinNotEmpty("+", tmpReturnCode, tmpBkReader.getFirstText("/TResponse/OrderInfo/PayStatus"), errorCode);
									retAts.payInfoCode = errorCode;
									String payType = tmpBkReader.getFirstText("/TResponse/OrderInfo/PayType");
									if (!StringHelper.isNullOrEmpty(payType)) {
										retAts.payType = convertPayTypeToS3(payType);
									} else {
									    retAts.payType = payType;
                                    }
								} else {
									retAts.respCode = "-1";
									retAts.respInfo = tmpBkReader.getFirstText("/TResponse/ResultInfo/Description");
								}
							} else {
								retAts.respCode = "-1";
								retAts.respInfo = tmpSbMsg.toString();
							}
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = "微保一码付订单状态查询本地验签失败!";
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "微保一码付订单状态查询返回内容为空,请联系微保相关技术人员!";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tradeRequestXml.getErrMsg();
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}
}
